package com.example.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo01 implements Runnable {
	private int tickets = 20;
// 创建公平锁
	private Lock lock = new ReentrantLock(true);

//	默认是非公平锁
//	private Lock lock = new ReentrantLock();

	public static void main(String[] args) {
		ReentrantLockDemo01 reentrantLockDemo01 = new ReentrantLockDemo01();
		for (int i = 0; i < 10; i++) {
			Thread thread = new Thread(reentrantLockDemo01, "thread" + i);
			thread.start();
			System.out.println("+==" + i);
		}
	}

	@Override
	public void run() {

		while (true) {
			try {
				lock.lock();
				if (tickets > 0) {
					TimeUnit.MILLISECONDS.sleep(10);
					System.out.println(Thread.currentThread().getName() + "---" + tickets--);
				} else {
					break;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}

		}

	}

}
